import React from 'react';
import { Form, Modal, Spin, Input, Button, Pagination, message } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
const { Search } = Input;

class ApiOrSlotModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      title: '',
      loading: true,
      list: [],
      total: 0,
      query: {
        page: 1,
        limit: 5,
        query: ''
      },
      type: ''
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  initData = (type) => {
    this.setState({
      visible: true,
      title: type === 'api' ? <FormattedMessage id="knowledgeManagement.overview.editingKnowledge.addApi" /> : <FormattedMessage id="knowledgeManagement.overview.editingKnowledge.addSlot" />,
      type,
    }, () => {
      switch (type) {
        case 'api':
          this.getApiList();
          break;
        case 'slot':
          this.getSlotList();
          break;
      }
    })
  }

  getApiList = () => {
    const { dispatch, currentUser } = this.props;
    const { query } = this.state;
    let apiQuery = {
      current: query.page,
      size: query.limit,
      apiNames: query.query
    }
    this.setState({ loading: true }, () => {
      dispatch({
        type: 'editingKnowledge/fetchApiList',
        payload: apiQuery,
        callback: res => {
          this.setState({
            list: res.records ? res.records : [],
            total: res.total,
            loading: false
          })
        },
      });
    })
  }

  getSlotList = () => {
    const { dispatch, currentUser } = this.props;
    const { query } = this.state;
    let slotQuery = {
      current: query.page,
      size: query.limit,
      search: query.query
    }
    this.setState({ loading: true }, () => {
      dispatch({
        type: 'editingKnowledge/fetchSlotList',
        payload: slotQuery,
        callback: res => {
          // console.log(res);
          this.setState({
            list: res.records ? res.records : [],
            total: res.total,
            loading: false
          })
        },
      });
    })
  }

  queryByPage = (page) => {
    let { query, type } = this.state;
    query.page = page;
    switch (type) {
      case 'api':
        this.getApiList();
        break;
      case 'slot':
        this.getSlotList();
        break;
    }
  }

  queryBySearch = (value) => {
    let { query, type } = this.state;
    query.query = value;
    query.page = 1;
    switch (type) {
      case 'api':
        this.getApiList();
        break;
      case 'slot':
        this.getSlotList();
        break;
    }
  }

  onChoose = (data) => {
    const { type } = this.state;
    switch (type) {
      case 'api':
        this.props.setApiData(data);
        this.closeModal();
        break;
      case 'slot':
        this.props.setSlotData(data);
        this.closeModal();
        break;
    }
  }

  goCreate = () => {
    const { type } = this.state;
    const { currentUser } = this.props;
    if (type === 'api' && currentUser.menus.knowledgeCenter.indexOf('customApi') === -1) {
      // return message.error('抱歉，您暂无权限访问新建词槽页面，请联系管理员授权');
      const msg= formatMessage({ id:'knowledgeManagement.overview.editingKnowledge.noPermission' })
       message.error(msg);
      
    }
    if (type === 'slot' && currentUser.menus.knowledgeCenter.indexOf('wordTroughManage') === -1) {
      // return message.error('抱歉，您暂无权限访问新建词槽页面，请联系管理员授权');
         const msg= formatMessage({ id:'knowledgeManagement.overview.editingKnowledge.noPermission' })
        return message.error(msg);
  
    };
    let url = '';
    switch (type) {
      case 'api':
        url = '/knowledgeDesign/customApi';
        break;
      case 'slot':
        url = '/knowledgeDesign/wordTroughManage';
        break;
    };
    const w = window.open('about:blank');
    w.location.href = url;
  }

  closeModal = () => {
    this.setState({
      visible: false,
      list: [],
      total: 0,
      query: {
        page: 1,
        limit: 5,
        query: ''
      },
    })
  }

  render() {
    const { visible, title, loading, list, total, query } = this.state;
    return (
      <Modal
        visible={visible}
        title={title}
        width={450}
        onCancel={this.closeModal}
        footer={null}
        closable
        destroyOnClose
      >
        <Spin spinning={loading}>
          <div>
            <Search
              placeholder={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.searchPlaeceholder'})}
              style={{ width: '70%', marginRight: 10 }}
              onSearch={this.queryBySearch}
            />
            <Button onClick={this.goCreate}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.addApi'})}</Button>
          </div>
          <div style={{ marginTop: 10 }}>
            {
              list.map(item => {
                return <div key={item.id} style={{ marginTop: 10 }}>
                  <Button
                    type={'primary'}
                    size={'small'}
                    style={{ marginRight: 10 }}
                    onClick={() => this.onChoose(item)}
                  >
                    {formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.choose' })}
                  </Button>
                  <span>{item.name}</span>
                </div>
              })
            }
          </div>
          <div style={{ textAlign: 'right', marginTop: 20 }}>
            <Pagination
              size="small"
              total={total}
              pageSize={5}
              current={query.page}
              onChange={this.queryByPage}
            />
          </div>
        </Spin>
      </Modal>
    )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(ApiOrSlotModal);
